<template>
  <div class="order-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="icon-arrow-left"></i>
        </button>
        <h1 class="page-title">我的订单</h1>
      </div>
    </div>

    <!-- 订单状态筛选 -->
    <div class="status-filter">
      <div 
        class="filter-item" 
        v-for="status in orderStatuses" 
        :key="status.value"
        :class="{ active: currentStatus === status.value }"
        @click="filterByStatus(status.value)"
      >
        {{ status.label }}
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-if="orders.length > 0">
      <div 
        class="order-item" 
        v-for="order in orders" 
        :key="order.id"
        @click="goToOrderDetail(order)"
      >
        <div class="order-header">
          <span class="order-number">{{ order.orderNumber }}</span>
          <span class="order-status" :class="getStatusClass(order.status)">
            {{ getStatusText(order.status) }}
          </span>
        </div>
        
        <div class="order-content">
          <div class="order-items">
            <div 
              class="order-item-product" 
              v-for="item in order.orderItems" 
              :key="item.id"
            >
              <img 
                v-if="item.productImage" 
                :src="item.productImage" 
                :alt="item.productName"
                class="product-image"
              />
              <div v-else class="product-image-placeholder">
                {{ item.productName }}
              </div>
              <div class="product-info">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-price">¥{{ item.price }} × {{ item.quantity }}</div>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-total">
              共{{ getTotalQuantity(order) }}件商品 合计：¥{{ order.totalAmount }}
            </div>
            <div class="order-actions">
              <button 
                v-if="order.status === 'PENDING'" 
                class="cancel-btn"
                @click.stop="cancelOrder(order)"
              >
                取消订单
              </button>
              <button 
                v-if="order.status === 'PENDING'" 
                class="pay-btn"
                @click.stop="payOrder(order)"
              >
                立即付款
              </button>
            </div>
          </div>
        </div>
        
        <div class="order-time">
          下单时间：{{ formatTime(order.createdAt) }}
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <div class="empty-icon">📦</div>
      <p class="empty-text">暂无订单</p>
    </div>

    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore">
      <button class="load-more-btn" @click="loadMore" :disabled="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useOrderStore } from '@/stores/order'
import { useUserStore } from '@/stores/user'
import type { Order } from '@/api/order'

// 路由
const router = useRouter()

// 状态管理
const orderStore = useOrderStore()
const userStore = useUserStore()

// 响应式数据
const currentStatus = ref('')
const currentPage = ref(0)
const pageSize = ref(10)

// 订单状态选项
const orderStatuses = [
  { value: '', label: '全部' },
  { value: 'PENDING', label: '待付款' },
  { value: 'PAID', label: '已付款' },
  { value: 'SHIPPED', label: '已发货' },
  { value: 'DELIVERED', label: '已送达' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' }
]

// 计算属性
const orders = computed(() => orderStore.orders)
const loading = computed(() => orderStore.loading)
const total = computed(() => orderStore.total)
const hasMore = computed(() => currentPage.value * pageSize.value < total.value)

// 生命周期
onMounted(() => {
  loadOrders()
})

// 方法
const loadOrders = async (page = 0) => {
  const userId = userStore.user?.id
  if (userId) {
    await orderStore.fetchOrders(userId, {
      page,
      size: pageSize.value,
      status: currentStatus.value
    })
  }
}

const filterByStatus = async (status: string) => {
  currentStatus.value = status
  currentPage.value = 0
  await loadOrders(0)
}

const loadMore = async () => {
  if (!hasMore.value || loading.value) return
  
  currentPage.value++
  const userId = userStore.user?.id
  if (userId) {
    await orderStore.fetchOrders(userId, {
      page: currentPage.value,
      size: pageSize.value,
      status: currentStatus.value
    })
  }
}

const goBack = () => {
  router.back()
}

const goToOrderDetail = (order: Order) => {
  router.push(`/order/${order.id}`)
}

const cancelOrder = async (order: Order) => {
  if (!confirm('确定要取消这个订单吗？')) {
    return
  }
  
  const userId = userStore.user?.id
  if (!userId || !order.id) return
  
  const result = await orderStore.cancelOrderById(userId, order.id)
  if (result.success) {
    alert('订单取消成功')
  } else {
    alert('取消订单失败: ' + result.message)
  }
}

const payOrder = (order: Order) => {
  // 这里实现支付逻辑
  alert('跳转到支付页面')
}

const getStatusClass = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'PENDING': 'pending',
    'PAID': 'paid',
    'SHIPPED': 'shipped',
    'DELIVERED': 'delivered',
    'COMPLETED': 'completed',
    'CANCELLED': 'cancelled'
  }
  return statusMap[status] || 'default'
}

const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'PENDING': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getTotalQuantity = (order: Order) => {
  if (!order.orderItems) return 0
  return order.orderItems.reduce((total, item) => total + item.quantity, 0)
}

const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.order-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.status-filter {
  display: flex;
  background-color: #fff;
  padding: 12px;
  overflow-x: auto;
  gap: 12px;
}

.filter-item {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f0f0f0;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.filter-item.active {
  background-color: #007bff;
  color: white;
}

.order-list {
  padding: 16px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.order-number {
  font-size: 14px;
  color: #666;
}

.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.order-status.pending {
  background-color: #fff3cd;
  color: #856404;
}

.order-status.paid {
  background-color: #d1ecf1;
  color: #0c5460;
}

.order-status.shipped {
  background-color: #d4edda;
  color: #155724;
}

.order-status.delivered {
  background-color: #cce5ff;
  color: #004085;
}

.order-status.completed {
  background-color: #d1e7dd;
  color: #0f5132;
}

.order-status.cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.order-items {
  margin-bottom: 12px;
}

.order-item-product {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item-product:last-child {
  border-bottom: none;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
}

.product-image-placeholder {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  text-align: center;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.product-price {
  font-size: 12px;
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.order-total {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.cancel-btn,
.pay-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.pay-btn {
  background-color: #007bff;
  color: white;
}

.order-time {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.empty-text {
  color: #666;
}

.load-more {
  padding: 20px;
  text-align: center;
}

.load-more-btn {
  padding: 12px 24px;
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  cursor: pointer;
}

.load-more-btn:disabled {
  background-color: #e9ecef;
  cursor: not-allowed;
}
</style>